<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import useUserStore from '@/store/modules/user'
import { ElMessage } from 'element-plus'

defineOptions({
  name: 'LoginForm',
})

const props = defineProps<{
  account?: string
}>()

const emits = defineEmits<{
  onLogin: [account: string]
  onRegister: [account: string]
  onResetPassword: [account: string]
}>()

const userStore = useUserStore()

const title = import.meta.env.VITE_APP_TITLE
const loading = ref(false)

// 登录方式，default 账号密码登录，qrcode 扫码登录
const type = ref('default')
const formRef = useTemplateRef<FormInstance>('formRef')
const form = ref({
  adminUserPhone: props.account ?? localStorage.login_account ?? '',
  adminUserPwd: '',
  remember: !!localStorage.login_account,
})
const rules = ref<FormRules>({
  adminUserPhone: [
    { required: true, trigger: 'blur', message: '请输入用户名' },
  ],
  adminUserPwd: [
    { required: true, trigger: 'blur', message: '请输入密码' },
    { min: 6, max: 18, trigger: 'blur', message: '密码长度为6到18位' },
  ],
})
function handleLogin() {
  formRef.value?.validate((valid) => {
    if (valid) {
      loading.value = true
      userStore.login(form.value).then(() => {
        if (form.value.remember) {
          localStorage.setItem('login_account', form.value.adminUserPhone)
        }
        else {
          localStorage.removeItem('login_account')
        }
        emits('onLogin', form.value.adminUserPhone)
      }).finally(() => {
        loading.value = false
      })
    }
  })
}

function testAccount(account: string) {
  form.value.adminUserPhone = account
  form.value.adminUserPwd = '123456'
  ElMessage({
    message: `登录接口`,
    type: 'success',
  })
  handleLogin()
}
</script>

<template>
  <ElForm ref="formRef" :model="form" :rules="rules" class="min-h-500px w-full flex-col-stretch-center p-12">
    <template v-if="type === 'default'">
      <h3 class="mb-8 text-xl color-[var(--el-text-color-primary)] font-bold">
        欢迎使用 {{ title }} !
      </h3>
      <div>
        <ElFormItem prop="account">
          <ElInput v-model="form.adminUserPhone" size="large" placeholder="用户名" type="text" tabindex="1">
            <template #prefix>
              <SvgIcon name="i-ri:user-3-fill" />
            </template>
          </ElInput>
        </ElFormItem>
        <ElFormItem prop="password">
          <ElInput
            v-model="form.adminUserPwd" type="password" size="large" placeholder="密码" tabindex="2" show-password
            @keyup.enter="handleLogin"
          >
            <template #prefix>
              <SvgIcon name="i-ri:lock-2-fill" />
            </template>
          </ElInput>
        </ElFormItem>
      </div>
      <ElButton
        :loading="loading" type="primary" size="large" style="width: 100%;"
        @click.prevent="testAccount('15123059793')"
      >
        登录
      </ElButton>
    </template>
  </ElForm>
</template>
